<template>
  <div class="meeting-room-reservation">
    <el-card class="filter-card">
      <el-form :inline="true" :model="filterForm" class="demo-form-inline">
        <el-form-item label="会议室名称">
          <el-input v-model="filterForm.roomName" placeholder="请输入会议室名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">搜索</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="list-card">
      <el-table :data="reservationList" stripe style="width: 100%" :row-style="{ height: '100px' }">
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="meetingRoomInfo.roomName" label="会议室名称"></el-table-column>
        <el-table-column prop="reservationInfo.startTime" label="开始时间"></el-table-column>
        <el-table-column prop="reservationInfo.endTime" label="结束时间"></el-table-column>
        <el-table-column prop="reservationInfo.attendeesCount" label="参会人数"></el-table-column>
        <el-table-column
          label="预订状态"
          :filters="[
            { text: '未支付', value: '1' },
            { text: '完成支付', value: '2' },
            { text: '退款审核中', value: '3' },
            { text: '取消成功', value: '4' },
            { text: '完成使用', value: '5' }
          ]"
          :filter-method="filterStatusHandler"
          filter-placement="bottom-end">
          
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.reservationInfo.status)">
              {{ getStatusText(scope.row.reservationInfo.status) }}
            </el-tag>
          </template>
          
        </el-table-column>
        <el-table-column prop="reservationInfo.amount" label="金额"></el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="mini" style="margin-right: 10px" @click="showRoomDetail(scope.row)">查看会议室详情</el-button>
            <el-button 
              style="margin-top: 10px;"
              size="mini" 
              type="danger" 
              :disabled="scope.row.reservationInfo.status === '5'"
              v-if="['2', '5'].includes(scope.row.reservationInfo.status)"
              @click="applyCancel(scope.row)">
              申请取消预定
            </el-button>
            <el-button 
              size="mini" 
              type="warning" 
              style="margin-top: 10px;"
              v-if="['4'].includes(scope.row.reservationInfo.status)"
              @click="showRefundRecord(scope.row)">
              查看退款记录
            </el-button>
            <el-button 
              style="margin-top: 10px;"
              size="mini" 
              type="danger" 
              :disabled="scope.row.reservationInfo.status === '5'"
              v-if="['1'].includes(scope.row.reservationInfo.status)"
              @click="">
              取消订单
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>

     <el-dialog v-model="roomDetailVisible" title="会议室详情">
      <el-descriptions :column="3" border>
        <el-descriptions-item label="会议室ID">
          {{ currentRoom.roomId }}
        </el-descriptions-item>
        <el-descriptions-item label="会议室名称">
          {{ currentRoom.roomName }}
        </el-descriptions-item>
        <el-descriptions-item label="会议室类型">
          {{ getRoomTypeText(currentRoom.roomType) }}
        </el-descriptions-item>
        <el-descriptions-item label="容纳人数">
          {{ currentRoom.capacity }}
        </el-descriptions-item>
        <el-descriptions-item label="投影仪">
          {{ currentRoom.hasProjector ? '有' : '无' }}
        </el-descriptions-item>
        <el-descriptions-item label="音响系统">
          {{ currentRoom.hasSoundSystem ? '有' : '无' }}
        </el-descriptions-item>
        <el-descriptions-item label="网络">
          {{ currentRoom.hasNetwork ? '有' : '无' }}
        </el-descriptions-item>
        <el-descriptions-item label="小时费率">
          {{ currentRoom.hourlyRate }}
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          {{ getRoomStatusText(currentRoom.status) }}
        </el-descriptions-item>
        <el-descriptions-item label="描述">
          {{ currentRoom.description }}
        </el-descriptions-item>
        <el-descriptions-item label="面积">
          {{ currentRoom.area }}平方米
        </el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        
      </div>
    </el-dialog>

    <el-dialog v-model="refundRecordVisible" title="退款记录">
      <el-table :data="refundRecords" stripe style="width: 100%">
        <el-table-column prop="refundId" label="退款ID"></el-table-column>
        <el-table-column label="退款金额">
          <template #default="scope">
            {{ scope.row.amount }}
          </template>
        </el-table-column>
        <el-table-column label="退款比例">
          <template #default="scope">
            {{ scope.row.refundRate * 100 }}%
          </template>
        </el-table-column>
        <el-table-column prop="processedAt" label="处理时间"></el-table-column>
        <el-table-column prop="reason" label="退款原因"></el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="refundRecordVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getReservationsByuserId } from '../../api/reservations';
import { addRefunds, getRefundsByRId } from '../../api/refunds';

export default {
  name: 'MeetingRoomReservation',
  data() {
    return {
      filterForm: {
        roomName: '',
        status: ''
      },
      reservationList: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      roomDetailVisible: false,
      currentRoom: {},
      refundRecordVisible: false,
      refundRecords: []
    };
  },
  created() {
    this.fetchReservations();
  },
  methods: {
    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        '1': '未支付',
        '2': '完成支付',
        '3': '退款审核中',
        '4': '取消成功',
        '5': '完成使用'
      };
      return statusMap[status] || '未知状态';
    },
    // 获取状态标签类型
    getStatusType(status) {
      const typeMap = {
        '1': 'info',
        '2': 'success',
        '3': 'warning',
        '4': 'danger',
        '5': 'primary'
      };
      return typeMap[status] || 'default';
    },
    // 获取会议室类型文本
    getRoomTypeText(type) {
      const typeMap = {
        '1': '教室型',
        '2': '圆桌型',
      };
      return typeMap[type] || '未知类型';
    },
    // 获取会议室状态文本
    getRoomStatusText(status) {
      const statusMap = {
        '1': '空闲',
        '2': '锁定',
        '3': '预定',
        '4': '使用',
        '5': '维护'
      };
      return statusMap[status] || '未知状态';
    },
    // 搜索预定记录
    search() {
      this.currentPage = 1;
      this.fetchReservations();
    },
    // 重置搜索条件
    resetFilter() {
      this.filterForm = {
        roomName: '',
        status: ''
      };
      this.search();
    },
    // 获取预定记录列表
    async fetchReservations() {
      try {
        const userId = JSON.parse(sessionStorage.getItem('user')).userId;
        const params = {
          userId,
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          ...this.filterForm
        };
        const response = await getReservationsByuserId(params);
        if (response.flag) {
          this.reservationList = response.result.records;
          console.log('jbbbbbb:', response);
          this.total = response.result.total;
        } else {
          this.$message.error(response.reason || '获取预定记录失败');
        }
      } catch (error) {
        console.error('获取预定记录出错:', error);
        this.$message.error('获取预定记录失败，请稍后重试');
      }
    },
    // 分页相关方法
    handleSizeChange(size) {
      this.pageSize = size;
      this.fetchReservations();
    },
    handleCurrentChange(page) {
      this.currentPage = page;
      this.fetchReservations();
    },
    // 显示会议室详情
    showRoomDetail(row) {
      if (!row || !row.meetingRoomInfo) {
        this.$message.error('会议室信息不存在');
        return;
      }
      this.currentRoom = row.meetingRoomInfo;
      this.roomDetailVisible = true;
      console.log(this.currentRoom);
      console.log('currentRoom:', this.currentRoom);
  console.log('roomId:', this.currentRoom.roomId);
  console.log('roomName:', this.currentRoom.roomName);
  console.log('roomType:', this.currentRoom.roomType);
  console.log('capacity:', this.currentRoom.capacity);
      this.$forceUpdate();
    },
    // 申请取消预定
    async applyCancel(row) {
      console.log('cancel clicked')
      const reservationId = row.reservationInfo.reservationId;
      const startTime = new Date(row.reservationInfo.startTime);
      const now = new Date();
      const hoursDiff = (startTime - now) / (1000 * 60 * 60);
      
      let refundRateText = '';
      if (hoursDiff >= 72) {
        refundRateText = '提前72小时以上，退全款';
      } else if (hoursDiff >= 48) {
        refundRateText = '提前48小时以上，退75%';
      } else if (hoursDiff >= 24) {
        refundRateText = '提前24小时以上，退25%';
      } else {
        refundRateText = '不足24小时，不予退款';
      }
      
      this.$prompt('退款规则：\n1. 提前72小时退全款；\n2. 提前48小时退75%；\n3. 提前24小时退25%。\n\n请输入取消预订的原因：', '取消预订申请', {
        confirmButtonText: '提交申请',
        cancelButtonText: '取消',
        inputPattern: /^.{1,200}$/,
        inputErrorMessage: '原因长度在1-200个字符之间'
      }).then(async ({ value }) => {
        try {
          const response = await addRefunds({ reservationId, reason: value });
          if (response.flag) {
            this.$message.success(response.reason || '申请取消预定成功');
            this.fetchReservations();
          } else {
            this.$message.error(response.reason || '申请取消预定失败');
          }
        } catch (error) {
          console.error('申请取消预定出错:', error);
          this.$message.error('申请取消预定失败，请稍后重试');
        }
      }).catch(() => {
        this.$message.info('已取消申请');
      });
    },
    // 显示退款记录
    async showRefundRecord(row) {
      try {
        const params = {
          reservationId: row.reservationInfo.reservationId
        };
        const response = await getRefundsByRId(params);
        if (response.flag) {
          this.refundRecords = response.result;
          this.refundRecordVisible = true;
        } else {
          this.$message.error(response.reason || '获取退款记录失败');
        }
      } catch (error) {
        console.error('获取退款记录出错:', error);
        this.$message.error('获取退款记录失败，请稍后重试');
      }
    },
    // 筛选预订状态
    filterStatusHandler(value, row) {
      return row.reservationInfo.status === value;
    }
  }
};
</script>

<style scoped>
.filter-card {
  margin-bottom: 15px;
}

.list-card {
  min-height: 400px;
}
</style>    